package com.saris.primego.web.controller.user;


import com.saris.primego.common.result.Result;
import com.saris.primego.pojo.vo.DishVO;
import com.saris.primego.service.DishService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Tag(name = "C端菜品")
public class DishController {
    private final DishService dishService;
    private final RedisTemplate<String,Object> redisTemplate;

    public DishController(DishService dishService, RedisTemplate<String,Object> redisTemplate) {
        this.dishService = dishService;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 根据分类id查询菜品
     */
    @GetMapping("/list")
    @Operation(summary = "按分类id查菜品")
    public Result<List<DishVO>> list(Long categoryId) {

        //构造redis中的key，规则：dish_分类id
        String key = "dish_" + categoryId;

        //查询redis中是否存在菜品数据
        List<DishVO> list = (List<DishVO>)redisTemplate.opsForValue().get(key);
        if (list != null && !list.isEmpty()) {
            //如果存在，直接返回，无须查询数据库
            return Result.success(list);
        }

        //如果不存在，查询数据库,起售中并在该分类的菜品,，将查询到的数据放入redis中
        list = dishService.listWithFlavor(categoryId);
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }

}
